package edu.uwlax.cs.oayonlinestore.client;

import java.util.ArrayList;
import java.util.Iterator;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import edu.uwlax.cs.oayonlinestore.client.utils.ExceptionTool;
import edu.uwlax.cs.oayonlinestore.vo.UserDetailsVO;

public class User extends UserDetailsVO implements AsyncCallback {

	public interface UserChangeListener {
		public void userChanged(User user);
	}

	private static final long serialVersionUID = 1L;

	private static User instance;

	public static User get() {
		if (instance == null)
			instance = new User();
		return instance;
	}

	private ArrayList listeners = new ArrayList();

	public User() {
	}

	public void addChangeListener(UserChangeListener l) {
		listeners.add(l);
	}

	public void onFailure(Throwable arg0) {
		Window.alert(ExceptionTool.extractUserMessage(arg0));		
	}

	public void onSuccess(Object arg0) {
		UserDetailsVO u = (UserDetailsVO) arg0;
		copy(u);
		for (Iterator i = listeners.iterator(); i.hasNext();)
			((UserChangeListener) i.next()).userChanged(this);
		Order.get().update();
	}

	public void removeChangeListener(UserChangeListener l) {
		listeners.remove(l);
	}

	public void update() {
		OnlinestoreRService.Util.getInstance().getLoggedInUser(this);
	}
}
